import 'dart:convert';
import 'package:dio/dio.dart';
import '../../config/app_const.dart';
import '../../utils/device_package_info.dart';
import '../../utils/encrypt_util.dart';
import '../../../utils/k_log.dart';

class HttpParameterSignInterceptor extends Interceptor {

  @override
  void onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    options.headers["Content-Type"] = "application/json; charset=utf-8";
    options.headers["X-Up-Timestamp"] = DateTime.now().millisecondsSinceEpoch;
    options.headers["X-Up-UA"] =
        "${await DevicePackageInfo.instance.getPackageName()}/${await DevicePackageInfo.instance.getAppVersion()}";
    options.headers["X-Up-Key"] = AppConst.djAppId;
    options.headers["X-Up-Signature"] = getHash(options);
    return handler.next(options);
  }

  String getHash(RequestOptions newRequest) {
    var stringBuffer = StringBuffer();
    stringBuffer.write(newRequest.method);
    stringBuffer.write("\n");
    if (newRequest.method == "POST") {
      KLog.d("requestString POST ${newRequest.data.toString()}");
      stringBuffer.write(
          EncryptUtil.encodeMd5(jsonEncode(newRequest.data)).toUpperCase());
      stringBuffer.write("\n");
    }
    stringBuffer.write("${newRequest.headers["Content-Type"]}");
    stringBuffer.write("\n");
    stringBuffer.write("${"X-Up-Key:"}${newRequest.headers["X-Up-Key"]}");
    stringBuffer.write("\n");
    stringBuffer
        .write("${"X-Up-Timestamp:"}${newRequest.headers["X-Up-Timestamp"]}");
    stringBuffer.write("\n");
    stringBuffer.write("${"X-Up-UA:"}${newRequest.headers["X-Up-UA"]}");
    stringBuffer.write("\n");
    stringBuffer.write(newRequest.path);
    var hash = stringBuffer.toString();
    var mD5 = EncryptUtil.encodeMd5(hash);
    return mD5;
  }
}
